//
//  RegistNextViewController.m
//  DaDaBao
//
//  Created by user on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "RegistNextViewController.h"

@interface RegistNextViewController ()<UITextFieldDelegate>
@property (nonatomic,copy)   NSString * phoneNum;

@property (nonatomic,strong) UIView * verifiCodeView;//验证码view
@property (nonatomic,strong) UIView * setPsdView;//设置密码view
@property (nonatomic,strong) UIView * veriPsdView;//再次设置密码view

@property (nonatomic,strong) UITextField * verifiTextField;//验证码
@property (nonatomic,strong) UITextField * psdTextField;//密码
@property (nonatomic,strong) UITextField * veriPsdTextField;//确认密码

@property (nonatomic,strong) UIButton    * registBtn;//注册按钮
@property (nonatomic,assign) int           statusInt;//计数
@property (nonatomic,strong) NSTimer     * timer;
@property (nonatomic,strong) UIButton    * verifiCodeBtn;
@end

@implementation RegistNextViewController
-(id)initWithPhoneNum:(NSString *)phoneNum
{
    if (self = [super init])
    {
        _phoneNum = phoneNum;
    }
    return self;
}
-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _statusInt = 60;
    
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    [self createTheNavigationBar];//创建导航栏
    
    UILabel * tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64.0f, SCREEN_WIDTH, 40*HSCALE)];
    tipLabel.text = [NSString stringWithFormat:@"短信已发送至%@",[self secureThePhoneNum:_phoneNum]];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tipLabel];
    
    [self createVerifiCodeView];//创建验证码view
    [self createThePsdView];//创建设置密码view
    [self createVerifiPSdView];//创建确认密码view
    
    _registBtn = [[UIButton alloc]initWithFrame:CGRectMake(10*WSCALE, 64 + 200*HSCALE, SCREEN_WIDTH - 20*WSCALE, 35*HSCALE)];
    [_registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [_registBtn addTarget:self action:@selector(buttonRegistTapped:) forControlEvents:UIControlEventTouchUpInside];
    _registBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    _registBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
    _registBtn.layer.cornerRadius = 5;
    _registBtn.layer.masksToBounds = TRUE;
    [self.view addSubview:_registBtn];

    if (!_timer)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];
        [_timer fire];
    }
}

//时间倒计时
-(void)timeCounting
{
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    if ([phoneVersion doubleValue] > 8.0) {
        [_verifiCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重试",_statusInt] forState:UIControlStateNormal];
    }
    else{
        _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
        _verifiCodeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重试",_statusInt] ;
    }
   
    
    if(_statusInt == 0)
    {
        if ([phoneVersion doubleValue] > 8.0)
        {
            [_verifiCodeBtn setTitle:@" 重新获取 " forState:UIControlStateNormal];
        }
        else
        {
            _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
            _verifiCodeBtn.titleLabel.text = @" 重新获取 " ;
        }
        
        _statusInt = 60;
        _verifiCodeBtn.enabled = TRUE;
        [_verifiCodeBtn setTitleColor:[UIColor hexStringToColor:RED_COLOR_VALUE] forState:UIControlStateNormal];
        _verifiCodeBtn.titleLabel.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        [_timer invalidate];
        _timer = nil;
        return;//直接返回
    }
     _statusInt -=1;
}
#pragma mark ------------创建导航栏
-(void)createTheNavigationBar
{
    [[UIApplication sharedApplication]setStatusBarHidden:FALSE];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [self.view addSubview:topView];
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 20.0f, SCREEN_WIDTH, 44.0f)];
    titleLab.backgroundColor = [UIColor clearColor];
    titleLab.font = [UIFont boldSystemFontOfSize:20.0f];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.text = @"用户注册";
    titleLab.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:titleLab];
    
    //返回按钮
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
}
#pragma mark--------创建验证码view
-(void)createVerifiCodeView
{
    _verifiCodeView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 40*HSCALE, SCREEN_WIDTH , 40*HSCALE)];
    _verifiCodeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_verifiCodeView];
    
    UILabel * verifiLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 80, 40*HSCALE)];
    verifiLabel.text = @"验证码";
    verifiLabel.textColor = RGBA(99, 98, 99, 1);
    [_verifiCodeView addSubview:verifiLabel];
    
    _verifiTextField = [[UITextField alloc]initWithFrame:CGRectMake(80, 0.0f, SCREEN_WIDTH - 170, 40*HSCALE)];
    _verifiTextField.placeholder = @"输入验证码";
    _verifiTextField.font = [UIFont systemFontOfSize:15.0f];
    _verifiTextField.delegate = self;
    _verifiTextField.keyboardType = UIKeyboardTypeNumberPad;

    [_verifiCodeView addSubview:_verifiTextField];
    
    UIView * lineView1 = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 10.0f *HSCALE, 1, 20*HSCALE)];
    lineView1.backgroundColor = [UIColor lightGrayColor];
    [_verifiCodeView addSubview:lineView1];
    
    _verifiCodeBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 0.0f, 90, 40*HSCALE)];
    _verifiCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _verifiCodeBtn.enabled = FALSE;//让它刚刚开始不可点击
    [_verifiCodeBtn setTitle:@"60秒后重试" forState:UIControlStateNormal];
    [_verifiCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_verifiCodeBtn addTarget:self action:@selector(buttonGetTheCodeTapped:) forControlEvents:UIControlEventTouchUpInside];
    [_verifiCodeView addSubview:_verifiCodeBtn];
    
}
#pragma mark-------------设置密码view
-(void)createThePsdView
{
    _setPsdView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 90*HSCALE, SCREEN_WIDTH , 40*HSCALE)];
    _setPsdView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_setPsdView];
    
    UILabel * setPsdLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40*HSCALE)];
    setPsdLabel.text = @"请设置密码";
    setPsdLabel.textColor = RGBA(99, 98, 99, 1);
    [_setPsdView addSubview:setPsdLabel];
    
    _psdTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 0.0f, SCREEN_WIDTH - 110, 40*HSCALE)];
    _psdTextField.placeholder = @"至少6位字符";
    _psdTextField.delegate = self;
    _psdTextField.font = [UIFont systemFontOfSize:15.0f];
    _psdTextField.secureTextEntry = TRUE;
    [_setPsdView addSubview:_psdTextField];
    
}
#pragma mark--------------确认密码view
-(void)createVerifiPSdView
{
    _veriPsdView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 140*HSCALE, SCREEN_WIDTH , 40*HSCALE)];
    _veriPsdView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_veriPsdView];
    
    UILabel * verifiPsdLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40*HSCALE)];
    verifiPsdLabel.text = @"请确认密码";
    verifiPsdLabel.textColor = RGBA(99, 98, 99, 1);
    [_veriPsdView addSubview:verifiPsdLabel];
    
    _veriPsdTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 0.0f, SCREEN_WIDTH - 110, 40*HSCALE)];
    _veriPsdTextField.placeholder = @"再次输入密码";
    _veriPsdTextField.delegate = self;
    _veriPsdTextField.font = [UIFont systemFontOfSize:15.0f];
    _veriPsdTextField.secureTextEntry = TRUE;
    [_veriPsdView addSubview:_veriPsdTextField];
    
    
}
#pragma mark--------------返回按钮绑定方法
-(void)buttonBackTapped:(id)sender
{
    [self dismissViewControllerAnimated:TRUE completion:nil];
}
#pragma mark -------------获取验证码按钮方法
-(void)buttonGetTheCodeTapped:(id)sender
{
    
    UIButton * codeBtn  = (UIButton *)sender;
    codeBtn.enabled = FALSE;//点击后，让不可再点击
   
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    [AppGlobalClass PostDataWithNSstring:REGIST_CODE withDictionary:@{@"mobileNumber":_phoneNum} success:^(NSDictionary *dictionary) {
        codeBtn.titleLabel.textColor = [UIColor grayColor];
        if (!_timer)
        {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];//开启定时器  倒计时结束后，在倒计时方法内使得按钮可以点击
            [_timer fire];
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

        codeBtn.enabled = TRUE;
    } networkerror:^(NSString *networkerror) {
        codeBtn.enabled = TRUE;
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    }];
}
#pragma mark--------------注册按钮绑定方法
-(void)buttonRegistTapped:(id)sender
{
    if (_verifiTextField.text.length<=0)
    {
        ALERT_VIEW(@"验证码不能为空");
        return;
    }
    if (_psdTextField.text.length<=0)
    {
        ALERT_VIEW(@"密码不能为空");
        return;
    }
    if (_psdTextField.text.length <6)
    {
        ALERT_VIEW(@"密码至少6位字符");
        return;
    }
    if (_veriPsdTextField.text.length<=0)
    {
        ALERT_VIEW(@"确认密码不能为空");
        return;
    }
    if (![_veriPsdTextField.text isEqualToString:_psdTextField.text])
    {
        ALERT_VIEW(@"两次密码不一致");
        return;
    }
    [self.view endEditing:TRUE];//让键盘下去
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    NSDictionary * postDict = @{@"mobile":_phoneNum,@"password":[AppGlobalClass md5:_psdTextField.text],@"checkCode":_verifiTextField.text};
    [AppGlobalClass PostDataWithNSstring:REGIST_URL withDictionary:postDict success:^(NSDictionary *dictionary) {
       if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
       {
        NSString * str = [dictionary objectForKey:@"message"];
        ALERT_VIEW(str);
        [self.presentingViewController.presentingViewController dismissViewControllerAnimated:TRUE completion:nil];
       }
       else{
           NSString * str = [dictionary objectForKey:@"message"];
           ALERT_VIEW(str);
       }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
 
    } networkerror:^(NSString *networkerror) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    }];
}
#pragma mark---------------uitextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *a = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (a.length>30) {
        
        return NO;
    }
    return YES;
}
-(NSString *)secureThePhoneNum:(NSString *)phoneNum
{
   return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
